class AsyncMessageQueue {
  constructor(batch = 1) {
    this.queue = []; // 存储待处理消息的队列
    this.isRunning = false; // 是否正在运行的标志
    this.batch = batch;
  }

  // 添加消息到队列
  enqueue(task) {
    this.queue.push(task);
    // this.run(); // 尝试运行队列
  }

  // 异步处理消息
  async processTask(task, exec) {
    try {
      await new Promise((resolve) => resolve(exec(task)));
      return true;
    } catch (error) {
      console.error(`Error processing task: ${error}`);
      return false; // 处理失败
    }
  }

  // 运行队列
  async run(exec) {
    if (this.queue.length === 0) {
      this.isRunning = false;
      return;
    }
    if (this.isRunning || this.queue.length === 0) return;
    this.isRunning = true;

    while (this.queue.length > 0) {
      let task = this.queue.splice(0, this.batch);
      // console.log(task, this.queue);
      let isSuccess = false;
      // 尝试处理并重试
      for (let attempt = 1; attempt <= 3; attempt++) {
        // 最多尝试3次
        isSuccess = await this.processTask(task, exec);
        if (isSuccess) break; // 成功则跳出循环
        console.log(`Retrying task... Attempt ${attempt}`);
      }
      if (!isSuccess) {
        console.warn(`Task failed after retries, data droped: ${task}`); //处理失败的数据丢弃，避免死循环
        //this.queue.push(...task); // 失败则重新加入队列末尾
      }
    }
    this.isRunning = false;
  }
}

// 使用示例
// const queue = new AsyncMessageQueue();
// queue.enqueue("Task 1");
// queue.enqueue("Task 2");
// queue.enqueue("Task 3");
// queue.run(2);
